package org.example.service.impl;

import com.jacob.activeX.ActiveXComponent;
import com.jacob.com.Dispatch;
import com.jacob.com.Variant;
import jakarta.annotation.Resource;
import org.example.pojo.Voice;
import org.example.service.TextToSpeechService;
import org.example.service.VoiceService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.nio.file.Files;
import java.nio.file.Paths;

/**
 * @author rjs
 */
@Service
public class TextToSpeechServiceImpl implements TextToSpeechService {

    private static final Logger logger = LoggerFactory.getLogger(TextToSpeechServiceImpl.class);

    @Resource
    private VoiceService voiceService;

    @Override
    public void textToSpeech(String text) {
        ActiveXComponent ax;
        try {
            ax = new ActiveXComponent("Sapi.SpVoice");

            // 运行时输出语音内容
            Dispatch spVoice = ax.getObject();

            // 下面是构建文件流把文字生成语音文件

            ax = new ActiveXComponent("Sapi.SpFileStream");
            Dispatch spFileStream = ax.getObject();

            ax = new ActiveXComponent("Sapi.SpAudioFormat");
            Dispatch spAudioFormat = ax.getObject();

            // 设置音频流格式
            Dispatch.put(spAudioFormat, "Type", new Variant(22));
            // 设置文件输出流格式
            Dispatch.putRef(spFileStream, "Format", spAudioFormat);
            // 调用输出 文件流打开方法，创建一个.mp3文件
            String filePath = "G:/NumbermanService/static/SpeechRecognition2.mp3";
            Dispatch.call(spFileStream, "Open", new Variant(filePath), new Variant(3), new Variant(true));
            // 设置声音对象的音频输出流为输出文件对象
            Dispatch.putRef(spVoice, "AudioOutputStream", spFileStream);
            // 设置音量 0到100
            Dispatch.put(spVoice, "Volume", new Variant(100));
            // 设置朗读速度
            Dispatch.put(spVoice, "Rate", new Variant(-2));
            // 开始朗读
            Dispatch.call(spVoice, "Speak", new Variant(text));

            // 关闭输出文件
            Dispatch.call(spFileStream, "Close");
            Dispatch.putRef(spVoice, "AudioOutputStream", null);

            spAudioFormat.safeRelease();
            spFileStream.safeRelease();
            spVoice.safeRelease();
            ax.safeRelease();

            // 读取生成的音频文件并转换为字节流
            byte[] voiceFile = Files.readAllBytes(Paths.get(filePath));

            // 创建一个新的Voice对象并将音频文件的字节流存储在其中
            Voice voice = new Voice();
            voice.setVoice(voiceFile);

            // 将Voice对象保存到数据库中
            voiceService.save(voice);

        } catch (Exception e) {
            // 使用日志框架记录错误信息
            logger.error("文本到语音转换期间出错", e);
        }
    }
}


